package com.example.demo.Shiro.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.example.demo.Shiro.entity.User;
import com.example.demo.Shiro.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2017-11-23
 */
@RestController
@RequestMapping("/shiro/user")
public class UserController {

    @Autowired
    private org.apache.shiro.mgt.SecurityManager securityManager;

    @Resource
    private IUserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Valid User user){
        //将SecurityManager创建到生产环境
        SecurityUtils.setSecurityManager(securityManager);
        //从SecurityUtils创建一个Subject
        Subject subject = SecurityUtils.getSubject();
        //Md5密码加密

        //认证提交认证token
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        String loginInfo = "登录成功";
        //执行登录操作
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e){
            loginInfo = "登录失败(账号错误或不存在)";
            e.printStackTrace();
        } catch (IncorrectCredentialsException e){
            loginInfo = "登录失败(密码错误)";
            e.printStackTrace();
        } catch (DisabledAccountException e){
            e.printStackTrace();
            loginInfo = "由于密码输入错误次数大于5次，帐号已经禁止登录！";
        }
        return loginInfo + ":" + user.getUsername();
    }

    @RequestMapping(value = "/register", method = RequestMethod.PUT)
    public String register(@Valid User user){
        Boolean flag = false;
        if (user !=null){
            EntityWrapper<User> ew = new EntityWrapper<>();
            ew.where("username={0}", user.getUsername());
            User userInDb = userService.selectOne(ew);
            if (userInDb == null){
                //MD5加密
                SimpleHash hash = new SimpleHash("md5",user.getPassword() , user.getUsername());
                String encodedPassword = hash.toHex();
                user.setPassword(encodedPassword);
                flag = userService.insert(user);
            }
        }
        return flag ? "注册成功" : "注册失败";
    }
}
